#define _CRT_SECURE_NO_WARNINGS 1
#include"heap.h"

void test() {
	Heap heap;
	HeapInit(&heap);
	HeapPush(&heap, 12);
	HeapPush(&heap, 2);
	HeapPush(&heap, 5);
	HeapPush(&heap, 1);
	HeapPush(&heap, 15);
	HeapPush(&heap, 16);
	HeapPush(&heap, 7);
	HeapPrint(&heap,heap.size);
	HeapPop(&heap);
	HeapPrint(&heap,heap.size);
	/*int ret = HeapTop(&heap);*/
	/*int ret = HeapSize(&heap);*/
	/*int ret = HeapEmpty(&heap);*/
}

void HeapSort(int* a, int n) {
	int i = 0;
	/*for (i = 0; i < n; i++) {
		AdjustUp(a, i);
	}*/
	for (i = (n - 2) / 2; i >= 0; i--) {
		AdjustDown(a, n, i);
	}
	for (i = n - 1; i > 0; i--) {
		Swep(&a[0],&a[i]);
		AdjustDown(a, i, 0);
	}
	int net = n - 1;
	while (i <= net) {
		Swep(&a[i], &a[net]);
		i++;
		net--;
	}

}

void CreateNDate() {
	int n = 10000;
	srand(time(NULL));
	FILE* data = fopen("data.txt", "w");
	if (data == NULL) {
		perror("CreateNDate->fopen");
		return;
	}
	int i = 0;
	for (i = 0; i < n; i++) {
		int x = rand() % 1000000;
		fprintf(data, "%d\n", x);
	}
	fclose(data);
}

void test2() {
	/*test();*/
	int arr[10] = { 15,21,1,54,3,5,10,14,19,9 };
	HeapSort(&arr, sizeof(arr) / sizeof(int));
	int i = 0;
	for (i = 0; i <sizeof(arr) / sizeof(int); i++) {
		printf("%d ", arr[i]);
	}
	printf("\n");
}

void Topk(int k) {
	FILE* data = fopen("data.txt", "r");
	if (data == NULL) {
		perror("CreateNDate->fopen");
		return;
	}
	int* arr;
	arr = (int*)malloc(sizeof(int) * k);
	if (arr == NULL) {
		perror("Topk->malloc");
		return;
	}
	int i = 0;
	for (i = 0; i < k; i++) {
		fscanf(data, "%d", &arr[i]);
	}
	HeapSort(arr, k);
	for (i = 0; i < 10000; i++) {
		int x = 0;
		fscanf(data, "%d", &x);
		if (x > arr[0]) {
			arr[0] = x;
			HeapSort(arr, k);
		}
		
	}
	for (i = 0; i < k; i++) {
		printf("%d ", arr[i]);
	}

	fclose(data);
	free(arr);
}


void HeapSort2(int* a, int n) {
	int i = 0;
	Heap heap;
	HeapInit(&heap);
	for (i = 0; i < n; i++) {
		HeapPush(&heap, a[i]);
	}
	for (i = n - 1; i > 0; i--) {
		Swep(&heap.array[0], &heap.array[i]);
		AdjustDown(heap.array, i, 0);
	}
	int net = n - 1;
	while (i <= net) {
		Swep(&heap.array[i], &heap.array[net]);
		i++;
		net--;
	}
	HeapPrint(&heap, n);
}

int main() {
	/*CreateNDate();*/
	int k = 10;
	Topk(k);
}